// chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
//     if (request.action === "exportTables") {
//         console.log("start")
//         exportTables(request.tabId);
//     }
// });
//

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "exportTables") {
        // 必须返回true以保持消息端口开放
        (async () => {
            try {
                // 1. 注入XLSX库
                await chrome.scripting.executeScript({
                    target: { tabId: request.tabId },
                    files: ['lib/xlsx.full.min.js']
                });

                // 2. 执行导出
                const results = await chrome.scripting.executeScript({
                    target: { tabId: request.tabId },
                    func: () => {
                        const tables = document.getElementsByTagName('table');
                        if (tables.length === 0) throw new Error("当前页面未找到表格");

                        const wb = XLSX.utils.book_new();
                        Array.from(tables).forEach((table, i) => {
                            const ws = XLSX.utils.table_to_sheet(table);
                            XLSX.utils.book_append_sheet(wb, ws, `Sheet${i+1}`);
                        });

                        XLSX.writeFile(wb, `export_${new Date().toISOString().slice(0,10)}.xlsx`);
                        return tables.length;
                    }
                });

                // 返回成功结果
                sendResponse({
                    success: true,
                    tableCount: results[0].result
                });
            } catch (error) {
                // 返回错误信息
                sendResponse({
                    success: false,
                    error: error.message
                });
            }
        })();

        // 必须返回true以使用异步sendResponse
        return true;
    }
});
